﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;

namespace WpfKinectUserControls
{
    public class SliderSlow : Slider
    {
        private bool _isDragging = false;
        public bool IsDragging
        {
            get { return _isDragging; }
        }
        public static readonly DependencyProperty ValueNDUProperty =
            DependencyProperty.RegisterAttached("ValueNDU", typeof(double), typeof(SliderSlow),
            new FrameworkPropertyMetadata(0D, new PropertyChangedCallback(OnValueNDUChanged), new CoerceValueCallback(CoerceValueNDU))
                {
                    BindsTwoWayByDefault = true,
                });

        private static object CoerceValueNDU(DependencyObject dObj, object val)
        {
            SliderSlow ctrl = (SliderSlow)dObj;
            var v = (double)val;
            if (v < ctrl.Minimum) v = ctrl.Minimum;
            if (v > ctrl.Maximum) v = ctrl.Maximum;
            return v;
        }

        private static void OnValueNDUChanged(DependencyObject dObj, DependencyPropertyChangedEventArgs e)
        {
            dObj.CoerceValue(ValueNDUProperty);
        }

        public double ValueNDU
        {
            get { return (double)this.GetValue(ValueNDUProperty); }
            set
            {
                if (value != ValueNDU)
                    this.SetValue(ValueNDUProperty, value);
                if (value != Value)
                    this.SetValue(ValueProperty, value);
            }
        }

        protected override void OnThumbDragStarted(DragStartedEventArgs e)
        {
            _isDragging = true;

            base.OnThumbDragStarted(e);
        }

        protected override void OnThumbDragCompleted(DragCompletedEventArgs e)
        {
            _isDragging = false;
            ValueNDU = this.Value;

            base.OnThumbDragCompleted(e);
        }

        protected override void OnValueChanged(double oldValue, double newValue)
        {
            if (!_isDragging)
                ValueNDU = this.Value;

            base.OnValueChanged(oldValue, newValue);
        }
    }
}
